#!/usr/bin/env python3

###############################################################################
# Name:        vkb.py
# Purpose:     virtual keyboard for linux
# Author:      Bright Li
# Modified by:
# Created:     2018-10-22
# Version:     [3.5.6]
# RCS-ID:      $$
# Copyright:   (c) Bright Li
# Licence:
###############################################################################

import sys, traceback
from signal import *
import argparse

from PyQt5.QtWidgets import QApplication
from PyQt5.QtDBus import QDBusConnection

from ui import KeyWnd

import py3func
LOG = py3func.make_logging(__file__)


def signal_interrupt(SIGINT, frame):
    LOG.debug("Signal Interrupt, I got you [Ctrl+C]")
    exit(1)

def getopt():
    parser = argparse.ArgumentParser("vkb", description="Virtual Keyboard【v3.5.5】2018/09/30")
    parser.add_argument("path_xml", action="store", help="the path of the [config].xml")
    parser.add_argument("-x", "--pos_x", action="store", type=int, help="position of the window: x")
    parser.add_argument("-y", "--pos_y", action="store", type=int, help="position of the window: y")
    parser.add_argument("-w", "--size_w", action="store", type=int, help="size of the window: width")
    parser.add_argument("-H", "--size_h", action="store", type=int, help="size of the window: height")
    return parser.parse_args()

def wnd_size(args):
    zero_num = 0
    list_geom = []
    for item in [args.pos_x, args.pos_y, args.size_w, args.size_h]:
        if not item:
            zero_num += 1
            list_geom.append(0)
        else:
            list_geom.append(int(item))

    # 尺寸判断-条件限制 ...
    return None if zero_num == 4 else list_geom

def dbus_conn(dbus_obj):
    session_bus = QDBusConnection.sessionBus()

    if not session_bus.isConnected():
        raise Exception("Fail to create a dbus connection.")

    if not QDBusConnection.sessionBus().registerService('org.i5os.virtkeyboard'):
        raise Exception("Fail to register the dbus service.")

    QDBusConnection.sessionBus().registerObject('/', dbus_obj
            , QDBusConnection.ExportNonScriptableSlots)
            # , QDBusConnection.ExportAllSlots)  ??


if __name__ == '__main__':
    try:
        signal(SIGINT, signal_interrupt)

        app = QApplication(sys.argv)
        args = getopt()
        win = KeyWnd(args.path_xml, wnd_size(args))
        dbus_conn(win)
        sys.exit(app.exec_())
    except Exception as e:
        LOG.error(e)
        # traceback.print_exc()
        sys.exit(-1)
